package com.wnhz.work.yz.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Selection;
import android.text.Spannable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.LookDetails2Bean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpdateDetialsActivity extends BaseActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_detials);
        initTilte();
        initData();
        initView();
    }

    private ExpandableListView expandableListView;
    private TextView tv_reset;
    private TextView tv_all_price;
    private int position;
    private String cardId;

    private void initData() {
        bean = (LookDetails2Bean) getIntent().getSerializableExtra("bean");
        position = getIntent().getIntExtra("position", 0);
        cardId = getIntent().getStringExtra("cardId");

    }

    private void initView() {
        findViewById(R.id.tv_reset).setOnClickListener(this);
        tv_all_price = (TextView) findViewById(R.id.tv_all_price);
        tv_reset = (TextView) findViewById(R.id.tv_reset);
        expandableListView = (ExpandableListView) findViewById(R.id.expanded_menu);
        tv_reset.setOnClickListener(this);
        setData();
    }

    private LookDetails2Bean bean = new LookDetails2Bean();


    private String getPrice() {
        double total = 0;
        for (int i = 0; i < bean.getInfo().size(); i++) {
            for (int j = 0; j < bean.getInfo().get(i).getData().size(); j++) {
                double nums = 1;
                try {
                    nums = Double.parseDouble(bean.getInfo().get(i).getData().get(j).getGoods_nums());
                } catch (Exception e) {
                    nums = 1;
                }
                double price = 0;
                try {
                    price = Double.parseDouble(bean.getInfo().get(i).getData().get(j).getGoods_price());
                } catch (Exception e) {
                    price = 0;
                }
                total += nums * price;
            }
        }
        return total + "";
    }

    private void setData() {
        tv_all_price.setText(getPrice());
        final List<LookDetails2Bean.InfoEntity> cate_info = bean.getInfo();
        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                for (int i = 0; i < cate_info.size(); i++) {
                    if (i == groupPosition)
                        expandableListView.expandGroup(i);
                }
            }
        });
        expandableListView.setAdapter(new BaseExpandableListAdapter() {
            @Override
            public int getGroupCount() {
                return cate_info.size();
            }

            @Override
            public int getChildrenCount(int groupPosition) {

                return cate_info.get(groupPosition).getData().size();
            }

            @Override
            public Object getGroup(int groupPosition) {
                return cate_info.get(groupPosition);
            }

            @Override
            public Object getChild(int groupPosition, int childPosition) {
                return cate_info.get(groupPosition).getData().get(childPosition);
            }

            @Override
            public long getGroupId(int groupPosition) {
                return groupPosition;
            }

            @Override
            public long getChildId(int groupPosition, int childPosition) {
                return childPosition;
            }

            @Override
            public boolean hasStableIds() {
                return false;
            }

            @Override
            public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
                GroupHolder holder;
                if (convertView == null) {
                    holder = new GroupHolder();
                    convertView = View.inflate(UpdateDetialsActivity.this, R.layout.item_group2, null);
                    holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                    holder.tv_all_number = (TextView) convertView.findViewById(R.id.tv_all_number);
                    convertView.setTag(holder);
                } else {
                    holder = (GroupHolder) convertView.getTag();
                }
                holder.tv_name.setText(cate_info.get(groupPosition).getCate_name() + "");
                holder.tv_all_number.setText("共" + cate_info.get(groupPosition).getData().size() + "件");

                return convertView;
            }

            class GroupHolder {
                TextView tv_name;
                TextView tv_all_number;
            }

            public Paint paint;

            public float measureTextLength(TextView tv) {
                if (paint == null) {
                    paint = new Paint();
                }
                paint.setTextSize(tv.getTextSize());
                return paint.measureText(tv.getText() + "");
            }

            @Override
            public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
                final AllocationViewHolder viewHolder;
                if (convertView == null) {
                    viewHolder = new AllocationViewHolder();
                    convertView = LayoutInflater.from(UpdateDetialsActivity.this).inflate(R.layout.all_look_content_item, null);
                    viewHolder.good_logo = (ImageView) convertView.findViewById(R.id.good_logo);
                    viewHolder.img_toast = (ImageView) convertView.findViewById(R.id.img_toast);
                    viewHolder.reduce = (ImageView) convertView.findViewById(R.id.reduce);
                    viewHolder.ll_add = (ImageView) convertView.findViewById(R.id.ll_add);
                    viewHolder.text_title = (TextView) convertView.findViewById(R.id.text_title);
                    viewHolder.text_price = (TextView) convertView.findViewById(R.id.text_price);
                    viewHolder.text_desc = (TextView) convertView.findViewById(R.id.text_desc);
                    viewHolder.shopping_number = (TextView) convertView.findViewById(R.id.shopping_number);
                    viewHolder.is_select = (LinearLayout) convertView.findViewById(R.id.is_select);
                    viewHolder.ll_toast = (LinearLayout) convertView.findViewById(R.id.ll_toast);
                    convertView.setTag(viewHolder);
                } else {
                    viewHolder = (AllocationViewHolder) convertView.getTag();
                }
                viewHolder.img_toast.setVisibility(View.GONE);
                viewHolder.img_toast.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (int i = 0; i < cate_info.get(groupPosition).getData().size(); i++) {
                            if (i == childPosition) {
                                cate_info.get(groupPosition).getData().get(childPosition).setSelect(!cate_info.get(groupPosition).getData().get(childPosition).isSelect());
                            } else {
                                cate_info.get(groupPosition).getData().get(childPosition).setSelect(false);
                            }
                        }
                        notifyDataSetChanged();
                    }
                });
                if (cate_info.get(groupPosition).getData().get(childPosition).isSelect()) {
                    viewHolder.is_select.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.is_select.setVisibility(View.GONE);
                }
                x.image().bind(viewHolder.good_logo, cate_info.get(groupPosition).getData().get(childPosition).getGoods_pic());
                viewHolder.text_title.setText(cate_info.get(groupPosition).getData().get(childPosition).getGoods_name());
                viewHolder.text_price.setText("¥" + cate_info.get(groupPosition).getData().get(childPosition).getGoods_price() + "/" + cate_info.get(groupPosition).getData().get(childPosition).getGoods_unit());


                if (cate_info.get(groupPosition).getData().get(childPosition).getGoods_unit() == null || cate_info.get(groupPosition).getData().get(childPosition).getGoods_unit().equals("")) {
                    viewHolder.text_price.setText("¥" + cate_info.get(groupPosition).getData().get(childPosition).getGoods_price() + "/套");
                }
                viewHolder.shopping_number.setText("" + cate_info.get(groupPosition).getData().get(childPosition).getGoods_nums());
                viewHolder.text_desc.setText(cate_info.get(groupPosition).getData().get(childPosition).getSku_info());
                viewHolder.ll_toast.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (measureTextLength(viewHolder.text_desc) >= viewHolder.text_desc.getWidth()) {
//                            Toast.makeText(context, "" + cate_info.get(groupPosition).getData().get(childPosition).getSku_info(), Toast.LENGTH_SHORT).show();
                            MyToast("" + cate_info.get(groupPosition).getData().get(childPosition).getSku_info());
                        }
                    }
                });
                //
                viewHolder.ll_add.setTag(viewHolder.shopping_number);
                viewHolder.ll_add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView textView = (TextView) v.getTag();
                        Double nums = 1.0;
                        try {
                            nums = Double.parseDouble(textView.getText().toString()) + 1.0;
                        } catch (Exception w) {
                            nums = 1.0;
                        }
                        textView.setText(nums + "");
                        cate_info.get(groupPosition).getData().get(childPosition).setGoods_nums(nums + "");
                        //
                        tv_all_price.setText(getPrice() + "");
                        notifyDataSetChanged();
                    }
                });
                viewHolder.reduce.setTag(viewHolder.shopping_number);
                viewHolder.reduce.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView textView = (TextView) v.getTag();
                        Double nums = 1.0;
                        try {
                            nums = Double.parseDouble(textView.getText().toString()) - 1.0;
                        } catch (Exception w) {
                            nums = 1.0;
                        }
                        if (nums == 0.0) {
                            Toast.makeText(UpdateDetialsActivity.this, "再减就没了", Toast.LENGTH_SHORT).show();
                            nums = 1.0;
                        }
                        textView.setText(nums + "");
                        cate_info.get(groupPosition).getData().get(childPosition).setGoods_nums(nums + "");
                        //
                        tv_all_price.setText(getPrice() + "");
                        notifyDataSetChanged();
                    }
                });
                final AllocationViewHolder finalViewHolder = viewHolder;
                viewHolder.shopping_number.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(UpdateDetialsActivity.this);
                        View view = View.inflate(UpdateDetialsActivity.this, R.layout.dialog_edit, null);
                        TextView queding1 = (TextView) view.findViewById(R.id.queding1);
                        TextView quxaio1 = (TextView) view.findViewById(R.id.quxiao1);
                        final EditText shopping_number = (EditText) view.findViewById(R.id.shopping_number);
                        shopping_number.setText(Double.parseDouble(cate_info.get(groupPosition).getData().get(childPosition).getGoods_nums()) + "");

                        shopping_number.postInvalidate();
                        //切换后将EditText光标置于末尾
                        CharSequence charSequence = shopping_number.getText();
                        if (charSequence instanceof Spannable) {
                            Spannable spanText = (Spannable) charSequence;
                            Selection.setSelection(spanText, charSequence.length());
                        }

                        builder.setView(view);
                        final AlertDialog show = builder.show();
                        Window dialogWindow = show.getWindow();
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        dialogWindow.setGravity(Gravity.CENTER);
//                lp.width = MyApplication.getInstance().window_w / 3; // 宽度
                        dialogWindow.setAttributes(lp);
                        queding1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Double nums = Double.parseDouble(cate_info.get(groupPosition).getData().get(childPosition).getGoods_nums());
                                try {
                                    nums = Double.parseDouble(shopping_number.getText().toString());
                                } catch (Exception e) {
                                    nums = Double.parseDouble(cate_info.get(groupPosition).getData().get(childPosition).getGoods_nums());
                                }
                                cate_info.get(groupPosition).getData().get(childPosition).setGoods_nums(nums + "");
                                viewHolder.shopping_number.setText("" + nums);
                                tv_all_price.setText(getPrice() + "");
                                show.dismiss();
                            }
                        });
                        quxaio1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                show.dismiss();
                            }
                        });

                    }
                });
                return convertView;
            }

            class AllocationViewHolder {
                ImageView good_logo, img_toast, reduce, ll_add;
                TextView text_title, text_price, text_desc;
                TextView shopping_number;
                LinearLayout is_select, ll_toast;
            }

            @Override
            public boolean isChildSelectable(int groupPosition, int childPosition) {
                return false;
            }
        });
        for (int i = 0; i < cate_info.size(); i++) {
            expandableListView.expandGroup(i);
        }
    }

    private void initTilte() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("单间配置");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.btn_main_right).setOnClickListener(this);
        TextView right = (TextView) findViewById(R.id.tv_right);
        right.setText("确定");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                showDialogv7("未添加至购物车，确认返回后将被清空！", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                break;
            //下一步
            case R.id.btn_main_right:
                Intent intent = new Intent();
                intent.putExtra("bean", bean);
                //   intent.putExtra("sku_id", skuId);
                intent.putExtra("position", position);
                intent.putExtra("total_price", getPrice());
                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.tv_reset:
                showDialogv7("是否重置？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        upLoad();
                    }
                });
                break;
        }
    }

    private void upLoad() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("budget_package_id", cardId);
        showDialog();
        XUtil.Post(Url.BATH_SEEPACKAGEGOODSLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        bean = gson.fromJson(result, LookDetails2Bean.class);
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                setData();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });
    }
}
